package com.oraking.android.hybridapp.dev.korealaw.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.oraking.android.hybridapp.dev.korealaw.R;
import com.oraking.android.hybridapp.dev.korealaw.holder.ParamHolder;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmFileUtil;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmHttpUtil;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmStr;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmStrUtil;
import com.oraking.android.hybridapp.dev.korealaw.util.CmmXmlUtil;
import com.oraking.android.hybridapp.dev.korealaw.xmlhandler.CmmXmlHandler;
import com.phonegap.DroidGap;

/**
 * 파일명          : KoreaLawList.java 
 * 작성일          : 2011. 10. 4.
 * 작성자          : <a href='http://oraking.springnote.com/' target='_blank'>Teddy</a>
 * Todo      :
 * 수정내용
 * -------------------------------------------------------------
 *      수정일      |      수정자      |              수정내용              
 * -------------------------------------------------------------
 *              |              |
 */

public class KoreaLawList extends DroidGap {

	Context mContext;
	Intent mIntent;
	
	WebView webView;
	ProgressDialog dial;	// ProgressBar
	
	
	String filePath;		// filePath 얻기
	
	// Handler 관련 상수 Start
	static final int PROGRESS_START = 0;
	static final int PROGRESS_STOP = 1;
	static final int HTML_SHOW = 2;
	static final int DATA_GET = 3;
	static final int ACTIVITY_SWITCH = 4;
	static final int MAKE_HTML = 5;
	static final int ERROR_MESSAGE = 6;
	// Handler 관련 상수 End
	
	ParamHolder paramHolder;	// Parameter 관련 클래스
	
	int page;
	
	@Override
	public void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		getResource();							// Resource 가져오기
		getIntentInfo();						// 넘긴데이터 구성
		configueScreen();						// 화면 구성하기
		mHandler.sendEmptyMessage(DATA_GET);	// 데이터 요청하기
	}
	
	// Data Communication 관련 Handler
	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case PROGRESS_START:
				dial.show();
				break;
			case PROGRESS_STOP:
				dial.dismiss();
				break;
			case HTML_SHOW:
				getSavedHTML();
				break;
			case ACTIVITY_SWITCH:
				break;
			case DATA_GET:
				getData();
				break;
			case MAKE_HTML:
				makeHTML((CmmXmlHandler) msg.obj);
				break;
			case ERROR_MESSAGE:
				Message toastMessage = Message.obtain();
				toastMessage.obj = msg.obj;
				toastHandler.sendMessage(toastMessage);
				break;
			default:
				break;
			}
		}
		
	};
	
	Handler toastHandler = new Handler(){
		boolean isShow = false;
		public void handleMessage(Message msg) {
			
			if(!isShow){
				isShow = true;
				Toast.makeText(KoreaLawList.this, String.valueOf(msg.obj), Toast.LENGTH_SHORT).show();
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(2000);
							isShow = false;
						} catch (InterruptedException e) {
						}
					}
				}).start();
			}
			
		};
	};
	
	/**
	 * @title  : 
	 * @location : com.oraking.android.hybridapp.dev.korealaw.activity.KoreaLawCn.configueScreen
	 * @writeDay : 2011. 10. 4. 오전 10:11:18
	 * @Todo  : TODO
	 */
	private void configueScreen() {
		// TODO Auto-generated method stub
		setContentView(R.layout.korealawlist);
		webView = (WebView) findViewById(R.id.webview);
		        
		// WebView Setting Start
		webView.setWebViewClient(new ProxyWebViewClient());						// WebViewClient 지정
		webView.addJavascriptInterface(new AdroidBridge(), "HybridApp");		// Bridge 인스턴스 등록
		webView.getSettings().setJavaScriptEnabled(true);						// Javascript 사용시 설정
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setLightTouchEnabled(true);
		webView.getSettings().setBuiltInZoomControls(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollbarOverlay(true);								// 웹뷰 오른쪽 스크롤바 공간 없애기 설정
		// WebView Setting End
	}
	
	// 리소스 구성 관련 Method
	private void getResource(){
		mIntent = getIntent();											// Intent 객체 얻기
		mContext = getApplicationContext();								// Content 객체 얻기
        filePath = mContext.getFilesDir().getPath()+"/";				// filePath 얻기
        Log.d("debug", "FILEPATH:"+ filePath);
        
        // ProgressDialog 리소스 얻기 Start
		dial = new ProgressDialog(KoreaLawList.this);
        dial.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dial.setMessage("Wait a monent...");
        // ProgressDialog 리소스 얻기 End
        
        page = 1;												// 처음일 경우 PageSetting
	}
	
	// 이전페이지에서 넘긴 값 가져오는 메소드
	private void getIntentInfo(){
		paramHolder = (ParamHolder) mIntent.getSerializableExtra("paramHolder");
	}
	
	// Http 통신해서 List 뿌려줄 데이터 가져오는 관련 Method
	private void getData(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				mHandler.sendEmptyMessage(PROGRESS_START);
				
				Message msg = Message.obtain();
    			String data = CmmHttpUtil.sendHttpPost(CmmStr.LAWURL+CmmStr.ACTION1, CmmHttpUtil.makeURL(paramHolder.keyword, paramHolder.selectChoice, page));
    			//Log.d("debug", "data:" + data);
    			CmmXmlHandler cmmXmlHandler = new CmmXmlHandler();
    			CmmXmlUtil.parseXml(data, cmmXmlHandler);
    			
    			msg.what = MAKE_HTML;
    			msg.obj = cmmXmlHandler;
    			
    			//Log.d("debug", "***************SIZE:"+cmmXmlHandler.getList().size());
    			
    			mHandler.sendMessage(msg);
			}
		}).start();
	}
	
	private void makeHTML(final CmmXmlHandler cmmXmlHandler){
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				CmmFileUtil.chkFile(filePath, CmmStr.LIST_CSS_PATH, CmmStr.LIST_CSS_FILES, KoreaLawList.this);		// CSS File 복사
				CmmFileUtil.chkFile(filePath, CmmStr.LIST_JS_PATH, CmmStr.LIST_JS_FILES, KoreaLawList.this);		// JS File 복사
				CmmFileUtil.chkFile(filePath, CmmStr.LIST_IMAGE_PATH, CmmStr.LIST_IMAGE_FILES, KoreaLawList.this);	// IMAGE File 복사
				
				CmmFileUtil.writeFile(filePath+"www/", CmmStr.HTML_LIST_FILE_NAME, CmmStr.HTML_LIST_START_TAG+CmmStrUtil.getListHtmlContent(cmmXmlHandler.getList())+CmmStr.HTML_LIST_END_TAG);
				mHandler.sendEmptyMessage(HTML_SHOW);
			}
		}).start();
	}
	
	// 저장된 HTML 가져오는 Mehtod
	private void getSavedHTML(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				webView.loadUrl("file://"+filePath+"www/"+CmmStr.HTML_LIST_FILE_NAME);
			}
		}).start();
	}
		
	private class AdroidBridge{
		@SuppressWarnings("unused")
		public void setMessage(final String str){
			new Thread(new Runnable() {
				@Override
				public void run() {
					Log.d("debug", "HybridApp : " + str);
					
					//상세페이지로 클릭한 경우
					if(str.startsWith("url=")){
						Intent mIntent = new Intent(KoreaLawList.this, KoreaLawContent.class);
						
						mIntent.putExtra("url", str.substring(4));
						
						//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(mIntent);
					}else if("up".equals(str)){
						if(page == 1){
							Message msg = Message.obtain();
							msg.what = ERROR_MESSAGE;
							msg.obj = CmmStr.ERROR_MESSAGE_5;
							mHandler.sendMessage(msg);
						}else{
							page--;
							mHandler.sendEmptyMessage(DATA_GET);	// 데이터 요청하기
						}
					}else if("down".equals(str)){
						page++;
						mHandler.sendEmptyMessage(DATA_GET);	// 데이터 요청하기
					}
				}
			}).start();
		}
	}
	
	private class ProxyWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			mHandler.sendEmptyMessage(PROGRESS_STOP);
			super.onPageFinished(view, url);
		}
	}
}
